package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.SportPlanTemplateEntity;

public class SportPlanTemplateDAO {
	public int insert(Connection conn, SportPlanTemplateEntity entity) throws SQLException {
		int id = -1;
		PreparedStatement ps = conn.prepareStatement(
				"insert into sport_plan_template(name,diet_tips,add_doc_id,add_time,status) values(?,?,?,?,?)",
				Statement.RETURN_GENERATED_KEYS);
		ps.setString(1, entity.getName());
		ps.setString(2, entity.getDiet_tips());
		ps.setInt(3, entity.getAdd_doc_id());
		ps.setTimestamp(4, entity.getAdd_time());
		ps.setInt(5, entity.getStatus());
		if (ps.executeUpdate() > 0) {
			ResultSet rSet = ps.getGeneratedKeys();
			if (rSet.next()) {
				id = rSet.getInt(1);
			}
		}
		return id;

	}

	public boolean update(Connection conn, SportPlanTemplateEntity entity) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn
				.prepareStatement("update sport_plan_template set name=?,diet_tips=?,add_doc_id=?,add_time=?,status=? where id=?");
		ps.setString(1, entity.getName());
		ps.setString(2, entity.getDiet_tips());
		ps.setInt(3, entity.getAdd_doc_id());
		ps.setTimestamp(4, entity.getAdd_time());
		ps.setInt(5, entity.getStatus());
		ps.setInt(6, entity.getId());
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;

	}

	public SportPlanTemplateEntity findById(Connection conn, int id) throws SQLException {
		SportPlanTemplateEntity entity = null;
		PreparedStatement ps = conn.prepareStatement("select * from sport_plan_template where id =? ");
		ps.setInt(1, id);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			entity = fill(rs);
		}
		return entity;
	}

	private SportPlanTemplateEntity fill(ResultSet rs) throws SQLException {
		SportPlanTemplateEntity entity = new SportPlanTemplateEntity();
		entity.setId(rs.getInt("id"));
		entity.setName(rs.getString("name"));
		entity.setAdd_time(rs.getTimestamp("add_time"));
		entity.setDiet_tips(rs.getString("diet_tips"));
		entity.setStatus(rs.getInt("status"));
		entity.setAdd_doc_id(rs.getInt("add_doc_id"));
		return entity;
	}

	public List<SportPlanTemplateEntity> listByDocID(Connection conn, int doc_id) throws SQLException {
		List<SportPlanTemplateEntity> list=new LinkedList<>();
		PreparedStatement ps = conn.prepareStatement("select * from sport_plan_template where add_doc_id =? ");
		ps.setInt(1, doc_id);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			SportPlanTemplateEntity entity = fill(rs);
			list.add(entity);
		}
		return list;
	}

}
